import { ref, reactive, type Ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { ApiResponse } from '@/types/api'

export interface UseFormOptions<T> {
  initialData?: Partial<T>
  rules?: FormRules
  onSuccess?: (data: T) => void
  onError?: (error: string) => void
  successMessage?: string
  errorMessage?: string
  resetAfterSubmit?: boolean
}

export interface FormActions<T> {
  submit: (submitFn: (data: T) => Promise<ApiResponse<T>>) => Promise<void>
  reset: () => void
  validate: () => Promise<boolean>
  setData: (data: Partial<T>) => void
  setLoading: (loading: boolean) => void
}

export function useForm<T extends Record<string, any>>(
  initialData: T,
  options: UseFormOptions<T> = {}
): {
  formData: T
  formRef: Ref<FormInstance | undefined>
  loading: Ref<boolean>
  errors: Ref<Record<string, string>>
  actions: FormActions<T>
} {
  const {
    rules,
    onSuccess,
    onError,
    successMessage = '操作成功',
    errorMessage = '操作失败',
    resetAfterSubmit = true
  } = options

  // 响应式数据
  const formData = reactive<T>({ ...initialData })
  const formRef = ref<FormInstance>()
  const loading = ref(false)
  const errors = ref<Record<string, string>>({})

  // 重置表单
  const reset = () => {
    Object.assign(formData, { ...initialData })
    formRef.value?.resetFields()
    errors.value = {}
  }

  // 验证表单
  const validate = async (): Promise<boolean> => {
    if (!formRef.value) return false
    
    try {
      await formRef.value.validate()
      return true
    } catch (error) {
      return false
    }
  }

  // 设置表单数据
  const setData = (data: Partial<T>) => {
    Object.assign(formData, data)
  }

  // 设置加载状态
  const setLoading = (loadingState: boolean) => {
    loading.value = loadingState
  }

  // 提交表单
  const submit = async (submitFn: (data: T) => Promise<ApiResponse<T>>) => {
    if (!formRef.value) return

    const isValid = await validate()
    if (!isValid) return

    loading.value = true
    errors.value = {}

    try {
      const response = await submitFn(formData)
      
      if (response.success) {
        ElMessage.success(response.message || successMessage)
        onSuccess?.(response.data)
        
        if (resetAfterSubmit) {
          reset()
        }
      } else {
        throw new Error(response.message || errorMessage)
      }
    } catch (error: any) {
      const errorMsg = error.response?.data?.message || error.message || errorMessage
      ElMessage.error(errorMsg)
      onError?.(errorMsg)
      
      // 处理字段级错误
      if (error.response?.data?.errors) {
        errors.value = error.response.data.errors
      }
    } finally {
      loading.value = false
    }
  }

  const actions: FormActions<T> = {
    submit,
    reset,
    validate,
    setData,
    setLoading
  }

  return {
    formData,
    formRef,
    loading,
    errors,
    actions
  }
}

// 通用的CRUD表单Hook
export function useCrudForm<T extends Record<string, any>>(
  initialData: T,
  options: UseFormOptions<T> & {
    createFn?: (data: T) => Promise<ApiResponse<T>>
    updateFn?: (id: string | number, data: T) => Promise<ApiResponse<T>>
  } = {}
) {
  const { createFn, updateFn, ...formOptions } = options
  const isEdit = ref(false)
  const editId = ref<string | number | null>(null)

  const form = useForm(initialData, formOptions)

  // 设置编辑模式
  const setEditMode = (id: string | number, data: Partial<T>) => {
    isEdit.value = true
    editId.value = id
    form.actions.setData(data)
  }

  // 设置创建模式
  const setCreateMode = () => {
    isEdit.value = false
    editId.value = null
    form.actions.reset()
  }

  // 提交表单（自动判断创建或更新）
  const submitForm = async () => {
    if (isEdit.value && updateFn && editId.value !== null) {
      await form.actions.submit((data) => updateFn(editId.value!, data))
    } else if (!isEdit.value && createFn) {
      await form.actions.submit(createFn)
    } else {
      ElMessage.error('缺少必要的操作函数')
    }
  }

  return {
    ...form,
    isEdit,
    editId,
    setEditMode,
    setCreateMode,
    submitForm
  }
}
